﻿using System;
using System.Web;
using System.Text.RegularExpressions;
using System.Text;

/// <summary>
/// Link factory class
/// </summary>
public class Link
{
    // regular expression that removes characters that aren't a-z, 0-9, dash, 
    // underscore or space
    private static Regex purifyUrlRegex = new Regex("[^-a-zA-Z0-9_ ]", RegexOptions.Compiled);

    // regular expression that changes dashes, underscores and spaces to dashes
    private static Regex dashesRegex = new Regex("[-_ ]+", RegexOptions.Compiled);

    // prepares a string to be included in an URL
    private static string PrepareUrlText(string urlText)
    {
        if (urlText != null)
        {
            urlText = HttpUtility.UrlEncode(urlText, Encoding.GetEncoding(28597)).Replace("+", " ");


            // remove all characters that aren't a-z, 0-9, dash, underscore or space
            urlText = purifyUrlRegex.Replace(urlText, "");

            // remove all leading and trailing spaces
            urlText = urlText.Trim();

            // change all dashes, underscores and spaces to dashes
            urlText = dashesRegex.Replace(urlText, "-");
        }

        // return the modified string    
        return urlText;
    }

    // Builds an absolute URL
    public static string BuildAbsolute(string relativeUri)
    {
        // get current uri
        Uri uri = HttpContext.Current.Request.Url;
        // build absolute path
        string app = HttpContext.Current.Request.ApplicationPath;
        if (!app.EndsWith("/")) app += "/";
        relativeUri = relativeUri.TrimStart('/');
        // return the absolute path
        return HttpUtility.UrlPathEncode(String.Format("http://{0}:{1}{2}{3}", uri.Host, uri.Port, app, relativeUri));
    }

    // Generate a department URL
    public static string ToCategory(string categoriaId, string page)
    {
        DetalhesCategoria c = CatalogAccess.GetDetalhesCategoria(categoriaId);
        string catUrlName = PrepareUrlText(c.Nome);

        // build category URL
        if (page == "1")
            return BuildAbsolute(String.Format("{0}-c{1}/", catUrlName, categoriaId));
        else
            return BuildAbsolute(String.Format("{0}-c{1}/Page-{2}/", catUrlName, categoriaId, page));
    }

    // Generate a category page without using url rewritter
    public static string ToCategoryWithoutRewritter(string categoriaId, string page)
    {
        if (page == "1")
            return BuildAbsolute(String.Format("Catalogo.aspx?categoriaID={0}", categoriaId));
        else
            return BuildAbsolute(String.Format("Catalogo.aspx?categoriaID={0}&Page={1}", categoriaId, page));
    }

    public static string ToCategoryWithoutRewritter(string categoriaId)
    {
        return ToCategoryWithoutRewritter(categoriaId, "1");
    }


    // Generate a product page without using url rewritter
    public static string ToProductWithoutRewritter(string produtoId, string page)
    {
        if (page == "1")
            return BuildAbsolute(String.Format("Produto.aspx?produtoID={0}", produtoId));
        else
            return BuildAbsolute(String.Format("Produto.aspx?produtoID={0}&Page={1}", produtoId, page));
    }

    public static string ToProductWithoutRewritter(string produtoId)
    {
        return ToProductWithoutRewritter(produtoId, "1");
    }

    // Generate a company page without using url rewritter
    public static string ToCompanyWithoutRewritter(string empresaId, string page)
    {
        if (page == "1")
            return BuildAbsolute(String.Format("Empresa.aspx?EmpresaID={0}", empresaId));
        else
            return BuildAbsolute(String.Format("Empresa.aspx?EmpresaID={0}&Page={1}", empresaId, page));
    }

    // Generate a company page without using url rewritter
    public static string ToDefaultWithoutRewritter(string page)
    {
        if (page == "1")
            return BuildAbsolute(String.Format("Default.aspx?Page=1"));
        else
            return BuildAbsolute(String.Format("Default.aspx?Page={0}", page));
    }

    public static string ToCompanyWithoutRewritter(string empresaId)
    {
        return ToCompanyWithoutRewritter(empresaId, "1");
    }

    // Generate a department URL for the first page
    public static string ToCategory(string categoriaId)
    {
        return ToCategory(categoriaId, "1");
    }

    public static string ToCompany(string empresaId)
    {
        // prepare product URL name
        DetalhesEmpresa p = CatalogAccess.GetDetalhesEmpresa(empresaId.ToString());
        string emprUrlName = PrepareUrlText(p.Nome);
        // build product URL
        return BuildAbsolute(String.Format("{0}-e{1}/", emprUrlName, empresaId));
    }


    public static string ToProduct(string productId)
    {
        // prepare product URL name
        DetalhesProduto p = CatalogAccess.GetDetalhesProduto(productId.ToString());
        string prodUrlName = PrepareUrlText(p.Nome);

        // build product URL
        return BuildAbsolute(String.Format("{0}-p{1}/", prodUrlName, productId));
    }

    public static string ToProductImage(string fileName)
    {
        // build product URL
        return BuildAbsolute("/ImagensProdutos/" + fileName);
    }

    public static string ToImagemLogotipo(string fileName)
    {
        // build product URL
        return BuildAbsolute("/ImagensBanners/" + fileName);
    }


    public static string ToImagemLogotipoEmpresa(string fileName)
    {
        // build company logotipo URL
        return BuildAbsolute("/ImagensLogos/" + fileName);
    }

    public static string ToSearch(string searchString, bool allWords, string page, string pageemp)
    {
        if (page == "1" && pageemp == "1")
            return BuildAbsolute(String.Format("/Busca.aspx?Search={0}&AllWords={1}", searchString, allWords.ToString()));
        else
            return BuildAbsolute(String.Format("/Busca.aspx?Search={0}&AllWords={1}&Page={2}&PageEmp={3}", searchString, allWords.ToString(), page, pageemp));
    }
}
